package net.wanho.interceptor;

import com.alibaba.druid.util.StringUtils;
import net.wanho.exception.UnauthorizedException;
import net.wanho.util.CurrentUtil;
import net.wanho.util.JwtUtil;
import org.apache.poi.util.StringUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求头中是否有token,如果没有，直接拒绝访问
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isEmpty(authorization)){
            throw new UnauthorizedException("请先登录再操作");
        }
        //如果有token,判断是否有效
        String token =authorization.replace("Bearer ","");
        if(!JwtUtil.valid(token)){
            throw new UnauthorizedException("token无效，请先登录");

        }
        //获取用户id,并保存到当前线程中
        CurrentUtil.setUserId(JwtUtil.decodeInteger(token,"userId"));
        JwtUtil.parseString(token,"userCode");
        return true;
    }
}
